package com.gupaoedu.vip.pattern.proxy.dbroute.proxy;

import com.gupaoedu.vip.pattern.proxy.dbroute.Order;
import com.gupaoedu.vip.pattern.proxy.dbroute.OrderService;
import com.gupaoedu.vip.pattern.proxy.dbroute.db.DynamicDataSourceEntity;
import com.sun.org.apache.xpath.internal.operations.Or;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;

public class DynamicProxyOrderService implements InvocationHandler {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

    private Object obj;

    public Object getInstance(Object obj){
        this.obj = obj;
        Class<?> clazz = obj.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Order order = (Order) args[0];
        for (Object obj : args) {
            System.out.println( obj.getClass().getMethod("getCreateTime",null).invoke(obj));
        }
        this.changeDbSource(Integer.valueOf(sdf.format(order.getCreateTime())));
        Object o = method.invoke(this.obj,args);
        this.restoreDbSource("1");
        return o;
    }

    public void changeDbSource(int year){
        System.out.println("切换数据源");
        DynamicDataSourceEntity.set(year);
    }

    public void restoreDbSource(String source){
        System.out.println("恢复数据源");
        DynamicDataSourceEntity.set(source);
    }
}
